package com.leet;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NQueen {
    List<List<String>> res;
    public boolean isValid(char[][] board,int r,int c,int n){
        for(int i = 0;i < n;i++){
            if(board[i][c]=='Q'){
                return false;
            }
        }
        //左下45
        for(int i=r-1,j=c-1;i>=0&&j>=0;i--,j--){
            if (board[i][j]=='Q'){
                return false;
            }
        }
        //左上45
        for(int i = r-1,j=c+1;i>=0&&j<n;i--,j++){
            if (board[i][j]=='Q'){
                return false;
        }

    }
        return true;
    }
    public List<String> toList(char[][] board){
        List<String> list = new ArrayList<>();
        for(char[] chars:board){
            list.add(chars.toString());
        }
        return list;
    }
    //从第一行走，一直往左上和左下看
    void backTracking(int n,int row,char[][] board ){
        if(row==n){
            res.add(toList(board));
            return;
        }
        for(int i = 0 ;i < n;i++){
            if(isValid(board,row,i,n)){
                board[row][i]='Q';
                backTracking(n,row+1,board);
                board[row][i]='.';
            }
        }
    }
    public List<List<String>> solveNQueens(int n) {
        res = new ArrayList<>();
        char[][] board = new char[n][n];
        for (char[] chars:board){
            //给每一行的array-string，fill'。'
            Arrays.fill(chars,'.');
        }
        backTracking(n,0,board);
        return res;

}
}
